<template>
  <div class="window-size-hook-demo p-4">
    <div class="space-y-6">
      <!-- 实时窗口尺寸显示 -->
      <div class="size-section">
        <h4 class="size-title">实时窗口尺寸</h4>
        <div class="size-display">
          <div class="size-metrics">
            <div class="metric-item">
              <div class="metric-label">宽度</div>
              <div class="metric-value">{{ windowSize.width.value }}px</div>
            </div>
            <div class="metric-item">
              <div class="metric-label">高度</div>
              <div class="metric-value">{{ windowSize.height.value }}px</div>
            </div>
            <div class="metric-item">
              <div class="metric-label">比例</div>
              <div class="metric-value">{{ aspectRatio }}</div>
            </div>
            <div class="metric-item">
              <div class="metric-label">设备类型</div>
              <div class="metric-value">{{ deviceType }}</div>
            </div>
          </div>

          <!-- 可视化窗口尺寸 -->
          <div class="size-visualization">
            <div class="window-frame" :style="windowFrameStyle">
              <div class="window-content">
                <div class="window-title">窗口预览</div>
                <div class="window-info">
                  {{ windowSize.width.value }} × {{ windowSize.height.value }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 响应式断点演示 -->
      <div class="size-section">
        <h4 class="size-title">响应式断点</h4>
        <div class="breakpoint-demo">
          <div class="breakpoint-indicators">
            <div class="breakpoint-item" :class="{ active: isMobile }">
              <div class="breakpoint-name">移动端</div>
              <div class="breakpoint-range">&lt; 768px</div>
              <div class="breakpoint-status">{{ isMobile ? '✅ 激活' : '❌ 未激活' }}</div>
            </div>

            <div class="breakpoint-item" :class="{ active: isTablet }">
              <div class="breakpoint-name">平板端</div>
              <div class="breakpoint-range">768px - 1024px</div>
              <div class="breakpoint-status">{{ isTablet ? '✅ 激活' : '❌ 未激活' }}</div>
            </div>

            <div class="breakpoint-item" :class="{ active: isDesktop }">
              <div class="breakpoint-name">桌面端</div>
              <div class="breakpoint-range">&gt; 1024px</div>
              <div class="breakpoint-status">{{ isDesktop ? '✅ 激活' : '❌ 未激活' }}</div>
            </div>
          </div>

          <!-- 当前激活的断点样式演示 -->
          <div class="responsive-demo">
            <div class="demo-container" :class="currentBreakpointClass">
              <div class="demo-content">
                <h5 class="demo-title">响应式布局演示</h5>
                <div class="demo-grid">
                  <div v-for="n in gridColumns" :key="n" class="demo-card">卡片 {{ n }}</div>
                </div>
                <p class="demo-description">
                  当前使用 <strong>{{ currentBreakpoint }}</strong> 布局， 显示
                  {{ gridColumns }} 列网格。
                </p>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 窗口变化历史 -->
      <div class="size-section">
        <h4 class="size-title">窗口变化历史</h4>
        <div class="space-y-3">
          <div class="history-controls">
            <button @click="clearHistory" class="clear-button">清空历史</button>
            <div class="history-stats">
              <span>变化次数: {{ resizeHistory.length }}</span>
              <span>最后更新: {{ lastUpdateTime }}</span>
            </div>
          </div>

          <div class="history-container">
            <div
              v-for="(record, index) in resizeHistory.slice(0, 10)"
              :key="index"
              class="history-item"
            >
              <div class="history-time">{{ record.time }}</div>
              <div class="history-size">{{ record.width }} × {{ record.height }}</div>
              <div class="history-change">
                <span v-if="record.widthChange" class="change-indicator">
                  宽度 {{ record.widthChange > 0 ? '+' : '' }}{{ record.widthChange }}px
                </span>
                <span v-if="record.heightChange" class="change-indicator">
                  高度 {{ record.heightChange > 0 ? '+' : '' }}{{ record.heightChange }}px
                </span>
              </div>
            </div>

            <div v-if="resizeHistory.length === 0" class="empty-history">
              调整窗口大小来查看变化历史
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Hook 说明 -->
    <div class="mt-6 p-4 bg-indigo-50 border border-indigo-200 rounded">
      <h5 class="text-sm font-medium text-indigo-800 mb-2">📏 useWindowSize Hook 特性</h5>
      <ul class="text-xs text-indigo-700 space-y-1">
        <li>• <strong>实时监听</strong>: 自动监听窗口大小变化事件</li>
        <li>• <strong>响应式数据</strong>: 返回响应式的宽度和高度引用</li>
        <li>• <strong>自动清理</strong>: 组件卸载时自动移除事件监听器</li>
        <li>• <strong>性能优化</strong>: 避免内存泄漏，合理管理事件监听</li>
        <li>• <strong>应用场景</strong>: 响应式布局、图表自适应、移动端适配等</li>
      </ul>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { useWindowSize } from '@/hooks/useWindowSize'

// 使用窗口大小 Hook
const windowSize = useWindowSize()

// 计算属性
const aspectRatio = computed(() => {
  if (windowSize.height.value === 0) return '0:0'
  const ratio = windowSize.width.value / windowSize.height.value
  return `${ratio.toFixed(2)}:1`
})

const deviceType = computed(() => {
  const width = windowSize.width.value
  if (width < 768) return '移动设备'
  if (width < 1024) return '平板设备'
  if (width < 1440) return '桌面设备'
  return '大屏设备'
})

// 响应式断点
const isMobile = computed(() => windowSize.width.value < 768)
const isTablet = computed(() => windowSize.width.value >= 768 && windowSize.width.value < 1024)
const isDesktop = computed(() => windowSize.width.value >= 1024)

const currentBreakpoint = computed(() => {
  if (isMobile.value) return '移动端'
  if (isTablet.value) return '平板端'
  return '桌面端'
})

const currentBreakpointClass = computed(() => {
  if (isMobile.value) return 'mobile-layout'
  if (isTablet.value) return 'tablet-layout'
  return 'desktop-layout'
})

const gridColumns = computed(() => {
  if (isMobile.value) return 1
  if (isTablet.value) return 2
  return 3
})

// 窗口可视化样式
const windowFrameStyle = computed(() => {
  const scale = Math.min(300 / windowSize.width.value, 200 / windowSize.height.value, 1)
  return {
    width: `${windowSize.width.value * scale}px`,
    height: `${windowSize.height.value * scale}px`,
    transform: `scale(${scale})`,
  }
})

// 窗口变化历史
interface ResizeRecord {
  time: string
  width: number
  height: number
  widthChange?: number
  heightChange?: number
}

const resizeHistory = ref<ResizeRecord[]>([])
const lastUpdateTime = ref('')

let previousWidth = windowSize.width.value
let previousHeight = windowSize.height.value

// 监听窗口大小变化
watch([windowSize.width, windowSize.height], ([newWidth, newHeight]) => {
  const now = new Date()
  const timestamp = now.toLocaleTimeString()

  const widthChange = newWidth - previousWidth
  const heightChange = newHeight - previousHeight

  resizeHistory.value.unshift({
    time: timestamp,
    width: newWidth,
    height: newHeight,
    widthChange: widthChange !== 0 ? widthChange : undefined,
    heightChange: heightChange !== 0 ? heightChange : undefined,
  })

  // 限制历史记录数量
  if (resizeHistory.value.length > 50) {
    resizeHistory.value = resizeHistory.value.slice(0, 50)
  }

  previousWidth = newWidth
  previousHeight = newHeight
  lastUpdateTime.value = timestamp
})

const clearHistory = () => {
  resizeHistory.value = []
  lastUpdateTime.value = ''
}
</script>

<style scoped lang="scss">
.window-size-hook-demo {
  @apply bg-gray-50;
}

.size-section {
  @apply p-4 bg-white rounded-lg border border-gray-200;
}

.size-title {
  @apply text-base font-semibold text-gray-800 mb-4 pb-2 border-b border-gray-200;
}

.size-display {
  @apply grid grid-cols-1 lg:grid-cols-2 gap-6;
}

.size-metrics {
  @apply grid grid-cols-2 gap-4;
}

.metric-item {
  @apply text-center p-4 bg-blue-50 rounded-lg border border-blue-200;
}

.metric-label {
  @apply text-sm text-blue-700 mb-1;
}

.metric-value {
  @apply text-2xl font-bold text-blue-800;
}

.size-visualization {
  @apply flex items-center justify-center p-4 bg-gray-100 rounded-lg;
}

.window-frame {
  @apply bg-white border-2 border-gray-400 rounded-lg overflow-hidden relative;
  transform-origin: center;
}

.window-content {
  @apply p-2 h-full flex flex-col items-center justify-center text-xs;
}

.window-title {
  @apply font-medium text-gray-700 mb-1;
}

.window-info {
  @apply text-gray-500;
}

.breakpoint-demo {
  @apply space-y-4;
}

.breakpoint-indicators {
  @apply grid grid-cols-1 md:grid-cols-3 gap-4;
}

.breakpoint-item {
  @apply p-4 border-2 border-gray-300 rounded-lg text-center transition-all;

  &.active {
    @apply border-green-500 bg-green-50;
  }
}

.breakpoint-name {
  @apply font-medium text-gray-800 mb-1;
}

.breakpoint-range {
  @apply text-sm text-gray-600 mb-2;
}

.breakpoint-status {
  @apply text-sm font-medium;
}

.responsive-demo {
  @apply p-4 bg-gray-100 rounded-lg;
}

.demo-container {
  @apply bg-white p-4 rounded border;

  &.mobile-layout {
    @apply border-red-300 bg-red-50;
  }

  &.tablet-layout {
    @apply border-yellow-300 bg-yellow-50;
  }

  &.desktop-layout {
    @apply border-green-300 bg-green-50;
  }
}

.demo-title {
  @apply text-lg font-medium mb-3;
}

.demo-grid {
  @apply grid gap-3 mb-3;

  .mobile-layout & {
    @apply grid-cols-1;
  }

  .tablet-layout & {
    @apply grid-cols-2;
  }

  .desktop-layout & {
    @apply grid-cols-3;
  }
}

.demo-card {
  @apply p-3 bg-white rounded border text-center text-sm;
}

.demo-description {
  @apply text-sm text-gray-600;
}

.history-controls {
  @apply flex justify-between items-center;
}

.clear-button {
  @apply px-3 py-1 bg-red-500 text-white rounded text-sm hover:bg-red-600;
}

.history-stats {
  @apply text-sm text-gray-600 space-x-4;
}

.history-container {
  @apply bg-gray-100 rounded-lg p-3 max-h-64 overflow-y-auto;
}

.history-item {
  @apply flex items-center justify-between p-2 bg-white rounded mb-2 text-sm;
}

.history-time {
  @apply text-gray-600 font-mono;
}

.history-size {
  @apply font-medium;
}

.history-change {
  @apply space-x-2;
}

.change-indicator {
  @apply text-xs px-2 py-1 rounded;

  &:first-child {
    @apply bg-blue-100 text-blue-700;
  }

  &:last-child {
    @apply bg-purple-100 text-purple-700;
  }
}

.empty-history {
  @apply text-center text-gray-500 py-4;
}
</style>
